from flask import Flask, request, jsonify
from flask_cors import CORS
import datetime
import logging
from logging import FileHandler
from views.company import bp_company
from views.user import bp_user
from utils.comm import Config
from utils.jwtfz import my_jwt
from utils.redisfz import r


def create_app():
    app = Flask(__name__)
    with app.app_context():
        pass
    return app


app = create_app()

app.register_blueprint(bp_company)
app.register_blueprint(bp_user)

app.config.from_object(Config)


@app.route('/aaa')
async def say_hello():
    str1 = '请求ip' + request.remote_addr + ',请求的url' + request.url + '错误信息' + '\n'
    app.logger.error(str1)
    return {'message': 'Hello!'}


# @app.before_request
# def before_request():
#     # 白名单
#     white = ['/login']
#     if request.path not in white:
#         try:
#             token = request.headers['Token']
#             print(token)
#         except:
#             return jsonify({'code': 403, 'msg': '无权访问'})
#         # 调用jwt解密token
#         if my_jwt.jwt_de(token) == False:
#             return jsonify({'code': 402, 'msg': 'token不合法'})
#         # 权限验证
#         payload = my_jwt.jwt_de(token)
#         uid = payload['data']['uid']
#         key = 'serve' + str(uid)
#         # 根据用户id获取接口权限
#         list1 = r.str_set(key)
#         if request.path not in list1:
#             return jsonify({'code': 10011, 'meg': '无权访问'})


cors = CORS(app)

if __name__ == "__main__":
    filename = datetime.datetime.strftime(datetime.datetime.now(), '%Y%m')
    handler = logging.FileHandler('logs/' + filename + '.txt', encoding='utf8')
    app.logger.addHandler(handler)
    app.run(debug=True)
